<template>
  <div class="app-container simple-app-container">
    <div v-loading="loading" v-permission="['base-data:product:info:add']">
      <a-form-model ref="form" :label-col="{span: 6}" :wrapper-col="{span: 14}" :model="formData" :rules="rules">
        <a-row v-if="$utils.isEmpty(productType)">
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品类型" required>
              <a-select v-model="productType">
                <a-select-option v-for="item in $enums.PRODUCT_TYPE.values()" :key="item.code" :value="item.code">{{ item.desc }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品名称" prop="name">
              <a-input v-model="formData.name" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品编号" prop="code">
              <a-input v-model="formData.code" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品简称" prop="shortName">
              <a-input v-model="formData.shortName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品类目" prop="categoryId">
              <product-category-selector v-model="formData.categoryId" :only-final="false" @input="selectCategory" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品品牌" prop="brandId">
              <product-brand-selector v-model="formData.brandId" :request-params="{ available: true }" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="规格" prop="spec">
              <a-input v-model="formData.spec" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col v-if="$enums.PRODUCT_TYPE.NORMAL.equalsCode(productType)" :md="8" :sm="24">
            <a-form-model-item label="重量（kg）" prop="weight">
              <a-input v-model="formData.weight" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col v-if="$enums.PRODUCT_TYPE.NORMAL.equalsCode(productType)" :md="8" :sm="24">
            <a-form-model-item label="体积（cm³）" prop="volume">
              <a-input v-model="formData.volume" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="商品属性" prop="skuPropertys">
              <a-select
                v-model="formData.skuPropertys"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择商品属性（可多选）"
                :filter-option="true"
                @change="skuPropertysHandleChange"
              >
                <a-select-option v-for="i in skuPropertyItems" :key="i.id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col v-for="modelor in modelorList" :key="modelor.id" :md="8" :sm="24">
            <a-form-model-item :label="modelor.name" :required="modelor.isRequired">
              <a-select
                v-if="$enums.COLUMN_TYPE.MULTIPLE.equalsCode(modelor.columnType)"
                v-model="modelor.text"
                mode="multiple"
                placeholder="请选择（可多选）"
                @select="modelorHandleSelect"
                @deselect="modelorHandleDeselect"
              >
                <a-select-option
                  v-for="item in modelor.items"
                  :key="item.name"
                  :value="modelor.id + '|' + item.id"
                >{{ item.name }}</a-select-option>
              </a-select>
              <a-select v-if="$enums.COLUMN_TYPE.SINGLE.equalsCode(modelor.columnType)" v-model="modelor.text" placeholder="请选择（可多选）">
                <a-select-option
                  v-for="item in modelor.items"
                  :key="item.id"
                  :value="item.id"
                >{{ item.name }}</a-select-option>
              </a-select>
              <div v-else-if="$enums.COLUMN_TYPE.CUSTOM.equalsCode(modelor.columnType)">
                <a-input-number v-if="$enums.COLUMN_DATA_TYPE.INT.equalsCode(modelor.columnDataType)" v-model="modelor.text" class="number-input" />
                <a-input-number v-else-if="$enums.COLUMN_DATA_TYPE.FLOAT.equalsCode(modelor.columnDataType)" v-model="modelor.text" :precision="2" class="number-input" />
                <a-input v-else-if="$enums.COLUMN_DATA_TYPE.STRING.equalsCode(modelor.columnDataType)" v-model="modelor.text" />
                <a-date-picker v-else-if="$enums.COLUMN_DATA_TYPE.DATE.equalsCode(modelor.columnDataType)" v-model="modelor.text" placeholder="" value-format="YYYY-MM-DD" />
                <a-time-picker
                  v-else-if="$enums.COLUMN_DATA_TYPE.TIME.equalsCode(modelor.columnDataType)"
                  v-model="modelor.text"
                  placeholder=""
                  value-format="HH:mm:ss"
                />
                <a-date-picker v-else-if="$enums.COLUMN_DATA_TYPE.DATE_TIME.equalsCode(modelor.columnDataType)" v-model="modelor.text" placeholder="" show-time value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <vxe-grid
              ref="grid"
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              height="360"
              :data="productSkus"
              :columns="[
                { type: 'checkbox', width: 40 },
                { field: 'skuCode', title: 'SKU编号', width: 120, align: 'center', slots: { default: 'product_sku_skuCode_default' ,header: 'product_sku_skuCode_header'}},
                { field: 'externalCode', title: '外部编号', width: 120, align: 'center', slots: { default: 'product_sku_externalCode_default' }},
                { field: 'skuPropertys', title: '多属性ID值', width: 200, align: 'center', slots: { default: 'product_sku_propertys_default' }, visible : false},
                { field: 'skuPropertysStr', title: '多属性', width: 200, align: 'center', slots: { default: 'product_sku_propertys_str_default',header: 'product_sku_propertys_header' }},
                { field: 'unit', title: '单位', width: 120, align: 'center', slots: { default: 'product_sku_unit_default' }},
                { field: 'purchasePrice', title: '采购价', width: 120, align: 'center', slots: { default: 'product_sku_purchasePrice_default', header: 'product_sku_purchasePrice_header' }},
                { field: 'salePrice', title: '销售价', width: 120, align: 'center', slots: { default: 'product_sku_salePrice_default' ,header: 'product_sku_salePrice_header'}},
                { field: 'retailPrice', title: '零售价', width: 120, align: 'center', slots: { default: 'product_sku_retailPrice_default' ,header: 'product_sku_retailPrice_header'}},
                { field: 'taxRate', title: '进项税率%', width: 120, align: 'center', slots: { default: 'product_sku_taxRate_default' }},
                { field: 'saleTaxRate', title: '销项税率%', width: 120, align: 'center', slots: { default: 'product_sku_saleTaxRate_default' }}
              ]"
              :toolbar-config="{
                // 缩放
                zoom: false,
                // 自定义表头
                custom: false,
                // 右侧是否显示刷新按钮
                refresh: false,
                // 自定义左侧工具栏
                slots: {
                  buttons: 'sku_toolbar_buttons'
                }
              }"
            >
              <!-- 工具栏 -->
              <template v-slot:sku_toolbar_buttons>
                <a-space>
                  <a-button @click="batchInputUnit">单位-批量</a-button>
                  <a-button @click="batchInputPurchasePrice">采购价-批量</a-button>
                  <a-button @click="batchInputSalePrice">销售价-批量</a-button>
                  <a-button @click="batchInputRetailPrice">零售价-批量</a-button>
                  <a-button @click="batchInputTaxRate">进项税率-批量</a-button>
                  <a-button @click="batchInputSaleTaxRate">销项税率-批量</a-button>
                </a-space>
              </template>

              <!-- SKU编号 列自定义表头 -->
              <template v-slot:product_sku_skuCode_header>
                <a-space>
                  <span>SKU编号<span style="color: red;padding: 2px 0px 0px 2px;">*</span></span>
                </a-space>
              </template>

              <!-- SKU编号 列自定义内容 -->
              <template v-slot:product_sku_skuCode_default="{ row }">
                <a-input v-model="row.skuCode" />
              </template>

              <!-- SKU外部编号 列自定义内容 -->
              <template v-slot:product_sku_externalCode_default="{ row }">
                <a-input v-model="row.externalCode" />
              </template>

              <!-- SKU属性 列自定义表头 -->
              <template v-slot:product_sku_propertys_header>
                <a-space>
                  <span>多属性<span style="color: red;padding: 2px 0px 0px 2px;">*</span></span>
                </a-space>
              </template>

              <!-- 多属性ID值 列自定义内容 -->
              <template v-slot:product_sku_propertys_default="{ row }">
                <a-input v-model="row.skuPropertys" read-only="readOnly"/>
              </template>

              <!-- 多属性 列自定义内容 -->
              <template v-slot:product_sku_propertys_str_default="{ row }">
                <a-input v-model="row.skuPropertysStr" read-only="readOnly" placeholder="请选择上方商品属性" />
              </template>

              <!-- SKU单位 列自定义内容 -->
              <template v-slot:product_sku_unit_default="{ row }">
                <a-input v-model="row.unit"/>
              </template>

              <!-- SKU采购价 列自定义表头 -->
              <template v-slot:product_sku_purchasePrice_header>
                <a-space>
                  <span>采购价<span style="color: red;padding: 2px 0px 0px 2px;">*</span></span>
                </a-space>
              </template>

              <!-- SKU采购价 列自定义内容 -->
              <template v-slot:product_sku_purchasePrice_default="{ row }">
                <a-input v-model="row.purchasePrice" class="number-input" />
              </template>

              <!-- 进项税率% 列自定义内容 -->
              <template v-slot:product_sku_taxRate_default="{ row }">
                <a-input v-model="row.taxRate" class="number-input" />
              </template>

              <!-- SKU销售价 列自定义表头 -->
              <template v-slot:product_sku_salePrice_header>
                <a-space>
                  <span>销售价<span style="color: red;padding: 2px 0px 0px 2px;">*</span></span>
                </a-space>
              </template>

              <!-- SKU销售价 列自定义内容 -->
              <template v-slot:product_sku_salePrice_default="{ row }">
                <a-input v-model="row.salePrice" class="number-input" />
              </template>

              <!-- 销项税率% 列自定义内容 -->
              <template v-slot:product_sku_saleTaxRate_default="{ row }">
                <a-input v-model="row.saleTaxRate" class="number-input" />
              </template>

              <!-- SKU零售价 列自定义表头 -->
              <template v-slot:product_sku_retailPrice_header>
                <a-space>
                  <span>零售价<span style="color: red;padding: 2px 0px 0px 2px;">*</span></span>
                </a-space>
              </template>

              <!-- SKU零售价 列自定义内容 -->
              <template v-slot:product_sku_retailPrice_default="{ row }">
                <a-input v-model="row.retailPrice" class="number-input" />
              </template>
            </vxe-grid>
          </a-col>
        </a-row>
      </a-form-model>
      <div class="form-modal-footer">
        <a-space>
          <a-button type="primary" @click="submit">保存</a-button>
          <a-button @click="closeDialog">关闭</a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>
<script>
import ProductBrandSelector from '@/components/Selector/ProductBrandSelector'
import ProductCategorySelector from '@/components/Selector/ProductCategorySelector'
import { validCode } from '@/utils/validate'

export default {
  name: 'AddProduct',
  components: {
    ProductBrandSelector, ProductCategorySelector
  },
  data() {
    return {
      // 是否显示加载框
      loading: false,
      // 表单数据
      formData: {},
      productType: 1,
      productBundles: [],
      // 属性列表
      modelorList: [],
      propertyList: [],
      // 商品SKU集合
      productSkus: [],
      // 商品属性数据
      skuPropertyItems: [],
      // 选中的商品属性值
      selectPropertyItems: [],
      // 表单校验规则
      rules: {
        code: [
          { required: true, message: '请输入商品编号' },
          { validator: validCode, message: '编号必须由字母、数字、“-_.”组成，长度不能超过20位' }
        ],
        name: [
          { required: true, message: '请输入商品名称' }
        ],
        categoryId: [
          { required: true, message: '请选择类目' }
        ],
        brandId: [
          { required: true, message: '请选择品牌' }
        ],
        weight: [
          {
            validator: (rule, value, callback) => {
              if (!this.$utils.isEmpty(value)) {
                if (!this.$utils.isFloat(value)) {
                  return callback(new Error('重量（kg）必须为数字'))
                }
                if (!this.$utils.isFloatGeZero(value)) {
                  return callback(new Error('重量（kg）不允许小于0'))
                }
                if (!this.$utils.isNumberPrecision(value, 2)) {
                  return callback(new Error('重量（kg）最多允许2位小数'))
                }
              }

              callback()
            }
          }
        ],
        volume: [
          {
            validator: (rule, value, callback) => {
              if (!this.$utils.isEmpty(value)) {
                if (!this.$utils.isFloat(value)) {
                  return callback(new Error('体积（cm³）必须为数字'))
                }
                if (!this.$utils.isFloatGeZero(value)) {
                  return callback(new Error('体积（cm³）不允许小于0'))
                }
                if (!this.$utils.isNumberPrecision(value, 2)) {
                  return callback(new Error('体积（cm³）最多允许2位小数'))
                }
              }

              callback()
            }
          }
        ],
        skuPropertys: [{ required: true, message: '请选择商品属性' }]
      }
    }
  },
  computed: {
  },
  created() {
    // 初始化表单数据
    this.initFormData()
  },
  methods: {
    // 关闭对话框
    closeDialog() {
      this.$utils.closeCurrentPage(this.$parent)
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {}

      this.modelorList = []

      this.skuPropertyItems = this.selectCategoryList({})
    },
    // 提交表单事件
    async submit() {
      const that = this
      let valid = true

      await this.$refs.form.validate((res) => {
        valid = res
      })

      if (!valid) {
        return
      }
      if (!this.$utils.isEmpty(this.modelorList)) {
        this.modelorList.filter(item => item.isRequired).every(item => {
          if (that.$utils.isEmpty(item.text)) {
            that.$msg.error(item.name + '不能为空！')
            valid = false
            return false
          }

          return true
        })
      }

      if (!valid) {
        return
      }

      // 校验SKU数据
      if (!this.validSkuData()) {
        return
      }

      const propertiesCover = []

      this.modelorList.filter(item => !this.$utils.isEmpty(item.text)).map(item => {
        const pro = {
          id: item.id
        }
        if (this.$utils.isArray(item.text)) {
          const textCover = []
          item.text.forEach(itemText => {
            textCover.push(itemText.split('|')[1])
          })
          pro.text = JSON.stringify(textCover)
        } else {
          pro.text = item.text.split('|')
        }
        propertiesCover.push(pro)
      })

      const params = Object.assign({}, this.formData, {
        properties: propertiesCover,
        productType: this.productType,
        productBundles: this.productBundles,
        skuItems: this.productSkus
      })

      this.loading = true
      this.$api.baseData.product.spu.create(params).then(res => {
        this.$msg.success('新增成功！')
        this.$emit('confirm')
        this.closeDialog()
      }).finally(() => {
        this.loading = false
      })
    },
    // 校验SKU数据
    validSkuData() {
      for (let i = 0; i < this.productSkus.length; i++) {
        const product = this.productSkus[i]

        if (this.$utils.isEmpty(product.skuCode)) {
          this.$msg.error('第' + (i + 1) + '行SKU编号不允许为空！')
          return false
        }

        if (this.$utils.isEmpty(product.purchasePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价不允许为空！')
          return false
        }
        if (!this.$utils.isFloat(product.purchasePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价必须为数字！')
          return false
        }
        if (!this.$utils.isFloatGeZero(product.purchasePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价不允许小于0！')
          return false
        }
        if (!this.$utils.isNumberPrecision(product.purchasePrice, 2)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价最多允许2位小数')
          return false
        }

        if (this.$utils.isEmpty(product.salePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品销售价不允许为空！')
          return false
        }
        if (!this.$utils.isFloat(product.salePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品销售价必须为数字！')
          return false
        }
        if (!this.$utils.isFloatGeZero(product.salePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品销售价不允许小于0！')
          return false
        }
        if (!this.$utils.isNumberPrecision(product.salePrice, 2)) {
          this.$msg.error('第' + (i + 1) + '行商品销售价最多允许2位小数')
          return false
        }

        if (this.$utils.isEmpty(product.retailPrice)) {
          this.$msg.error('第' + (i + 1) + '行商品零售价不允许为空！')
          return false
        }
        if (!this.$utils.isFloat(product.retailPrice)) {
          this.$msg.error('第' + (i + 1) + '行商品零售价必须为数字！')
          return false
        }
        if (!this.$utils.isFloatGeZero(product.retailPrice)) {
          this.$msg.error('第' + (i + 1) + '行商品零售价不允许小于0！')
          return false
        }
        if (!this.$utils.isNumberPrecision(product.retailPrice, 2)) {
          this.$msg.error('第' + (i + 1) + '行商品零售价最多允许2位小数')
          return false
        }

        // 进项税率不为空时验证格式
        if (!this.$utils.isEmpty(product.taxRate)) {
          if (!this.$utils.isInteger(product.taxRate)) {
            this.$msg.error('第' + (i + 1) + '行销项税率%必须为整数')
            return false
          }
          if (!this.$utils.isIntegerGeZero(product.taxRate)) {
            this.$msg.error('第' + (i + 1) + '行销项税率%不允许小于0')
            return false
          }
        }

        // 销售税率不为空时验证格式
        if (!this.$utils.isEmpty(product.saleTaxRate)) {
          if (!this.$utils.isInteger(product.saleTaxRate)) {
            this.$msg.error('第' + (i + 1) + '行销售税率%必须为整数')
            return false
          }
          if (!this.$utils.isIntegerGeZero(product.saleTaxRate)) {
            this.$msg.error('第' + (i + 1) + '行销售税率%不允许小于0')
            return false
          }
        }

        return true
      }
    },
    selectCategory(val) { // 选择商品类目后触发事件
      this.modelorList = []
      if (!this.$utils.isEmpty(val)) {
        this.$api.baseData.product.property.getModelorByCategory(val).then(res => {
          this.modelorList = res
          // 设置商品属性默认按照商品分类绑定的属性
          if (this.$utils.isArray(res) && res.length > 0) {
            const categoryProperty = []
            for (let i = 0, j = this.modelorList.length; i < j; i++) {
              categoryProperty.push(this.modelorList[i].id)
            }
            this.formData.skuPropertys = categoryProperty
            // 已选中的属性清空
            this.selectPropertyItems = []
            // 清空现有SKU数据
            this.productSkus = []
          }
        })
      }
    },
    selectCategoryList(val) { // 查询商品属性
      this.skuPropertyItems = []
      this.$api.baseData.product.property.select(val).then(res => {
        this.skuPropertyItems = res
      })
    },
    addRow() {
      this.productBundles.push(this.emptyProduct())
    },
    emptyProduct() {
      return {
        id: this.$utils.uuid(),
        productId: ''
      }
    },
    delRow() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择要删除的商品数据！')
        return
      }

      this.$msg.confirm('是否确定删除选中的商品？').then(() => {
        this.productBundles = this.productBundles.filter(t => {
          const tmp = records.filter(item => item.id === t.id)
          return this.$utils.isEmpty(tmp)
        })
      })
    },
    skuPropertysHandleChange(value) { // 商品属性值改变触发事件
      if (value.length > 0 && this.$utils.isArray(value)) {
        let ids = ''
        value.forEach((v, i) => {
          ids += v + ','
        })
        this.$api.baseData.product.property.getModelorByIds(ids).then(res => {
          // 设置商品属性默认按照商品分类绑定的属性
          if (this.$utils.isArray(res)) {
            this.modelorList = res
            // 已选中的属性清空
            this.selectPropertyItems = []
          }
        })
      } else {
        this.modelorList = []
      }
    },
    modelorHandleSelect(value, option) { // 选中属性Item值选中事件
      const arr = value.split('|')
      // [
      //   {
      //     parentId: '',
      //     selected: [{
      //       id: '',
      //       name: ''
      //     }]
      //   }
      //   ]
      const p = {
        parentId: arr[0],
        selected: []
      }
      const s = {
        id: arr[1],
        name: option.key
      }
      p.selected.push(s)

      if (this.selectPropertyItems.length > 0) {
        const indx = this.selectPropertyItems.findIndex(item => item.parentId === arr[0])
        if (indx !== -1) {
          for (let i = 0, j = this.selectPropertyItems.length; i < j; i++) {
            if (this.selectPropertyItems[i].parentId === arr[0]) {
              this.selectPropertyItems[i].selected.push(s)
            }
          }
        } else {
          this.selectPropertyItems.push(p)
        }
      } else {
        this.selectPropertyItems.push(p)
      }

      // const jsonstr = JSON.stringify(this.selectPropertyItems)
      // console.log(jsonstr)
      const itemArr = []
      if (this.selectPropertyItems.length > 0) {
        for (let i = 0, j = this.selectPropertyItems.length; i < j; i++) {
          if (this.selectPropertyItems[i].selected.length > 0) {
            const itemIds = []
            this.selectPropertyItems[i].selected.forEach(item => { itemIds.push(item.id) })
            itemArr.push(itemIds)
          }
        }
      }
      // console.log(JSON.stringify(itemArr))
      var skuItemArr = this.getSkuDkrj(itemArr)
      // const jsonstr2 = JSON.stringify(skuItemArr)
      // console.log(jsonstr2)
      this.setSkuData(skuItemArr)
    },
    modelorHandleDeselect(value, option) { // 选中属性Item值取消选中事件
      const arr = value.split('|')
      for (let i = 0, j = this.selectPropertyItems.length; i < j; i++) {
        if (this.selectPropertyItems[i].parentId === arr[0]) {
          this.selectPropertyItems[i].selected = this.selectPropertyItems[i].selected.filter(item => item.id !== arr[1])
        }
      }
      // const jsonstr = JSON.stringify(this.selectPropertyItems)
      // console.log(jsonstr)

      const itemArr = []
      if (this.selectPropertyItems.length > 0) {
        for (let i = 0, j = this.selectPropertyItems.length; i < j; i++) {
          if (this.selectPropertyItems[i].selected.length > 0) {
            const itemIds = []
            this.selectPropertyItems[i].selected.forEach(item => { itemIds.push(item.id) })
            itemArr.push(itemIds)
          }
        }
      }
      // const arr1 = ['AAA', 'BBB']
      // const arr2 = ['张三', '李四']
      // const arr3 = ['红色', '蓝色']
      // itemArr.push(arr1)
      // itemArr.push(arr2)
      // itemArr.push(arr3)
      // console.log(JSON.stringify(itemArr))
      var skuItemArr = this.getSkuDkrj(itemArr)
      // const jsonstr2 = JSON.stringify(skuItemArr)
      // console.log(jsonstr2)
      this.setSkuData(skuItemArr)
    },
    getSkuDkrj(arr) { // 计算商品SKU笛卡尔积
      if (arr.length === 0) {
        return []
      } else if (arr.length === 1) {
        return arr[0]
      } else {
        var result = []
        var firstArr = arr[0]
        var remainingArr = this.getSkuDkrj(arr.slice(1))
        for (var i = 0; i < firstArr.length; i++) {
          for (var j = 0; j < remainingArr.length; j++) {
            result.push([firstArr[i]].concat(remainingArr[j]))
          }
        }
        return result
      }
    },
    setSkuData(skuItemArr) { // SKU笛卡尔积数据放入表格
      this.productSkus = []
      if (skuItemArr.length > 0) {
        for (let i = 0, j = skuItemArr.length; i < j; i++) {
          const item = skuItemArr[i]
          var propertyIds = ''
          var propertyStrs = ''
          if (!this.$utils.isArray(item)) {
            propertyIds += item + ','
            for (let a = 0, b = this.selectPropertyItems.length; a < b; a++) {
              if (this.selectPropertyItems[a].selected.length > 0) {
                this.selectPropertyItems[a].selected.forEach(si => {
                  if (si.id === item) {
                    propertyStrs += si.name + '/'
                  }
                })
              }
            }
          } else {
            item.forEach(e => {
              propertyIds += e + ','
              for (let a = 0, b = this.selectPropertyItems.length; a < b; a++) {
                if (this.selectPropertyItems[a].selected.length > 0) {
                  this.selectPropertyItems[a].selected.forEach(si => {
                    if (si.id === e) {
                      propertyStrs += si.name + '/'
                    }
                  })
                }
              }
            })
          }
          const skuLine = {
            skuCode: 1001 + i,
            externalCode: '',
            unit: '',
            skuPropertys: propertyIds.substr(0, propertyIds.length - 1),
            skuPropertysStr: propertyStrs.substr(0, propertyStrs.length - 1),
            purchasePrice: 0.00,
            salePrice: 0.00,
            retailPrice: 0.00,
            taxRate: 13,
            saleTaxRate: 13
          }

          this.productSkus.push(skuLine)
        }
      }
    },
    // 批量录入单位
    batchInputUnit() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入单位', {
        inputValue: '个',
        title: '批量调整商品单位'
      }).then(({ value }) => {
        records.forEach(t => {
          t.unit = value
        })
      })
    },
    // 批量录入采购价
    batchInputPurchasePrice() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入采购价（元）', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '采购价（元）必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整采购价'
      }).then(({ value }) => {
        records.forEach(t => {
          t.purchasePrice = value
        })
      })
    },
    // 批量录入销售价
    batchInputSalePrice() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入销售价（元）', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '销售价（元）必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整销售价'
      }).then(({ value }) => {
        records.forEach(t => {
          t.salePrice = value
        })
      })
    },
    // 批量录入零售价
    batchInputRetailPrice() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入零售价（元）', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '零售价（元）必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整零售价'
      }).then(({ value }) => {
        records.forEach(t => {
          t.retailPrice = value
        })
      })
    },
    // 批量录入进项税率
    batchInputTaxRate() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入进项税率', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '进项税率必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整进项税率'
      }).then(({ value }) => {
        records.forEach(t => {
          t.taxRate = value
        })
      })
    },
    // 批量录入销项税率
    batchInputSaleTaxRate() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入销项税率', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '销项税率必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整销项税率'
      }).then(({ value }) => {
        records.forEach(t => {
          t.saleTaxRate = value
        })
      })
    }
  }
}
</script>
